//index.js
const wxaUserService = require('../../../api/wxaUserService.js')
const bannerService = require('../../../api/bannerService.js')
const memberService = require('../../../api/memberService.js')
const couponService = require('../../../api/couponService.js')
const auth = require('../../../utils/auth.js')
const utils = require('../../../utils/utils.js')

//获取应用实例
const app = getApp()

Page({
  data: {
    userInfo: {},
    hasUserInfo: false,
    showModel: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    mobile: '',
    bindMobile: '',
    memberId: '',
    couponCount: '*', // 券数量
    storedValue: '*', // 储值余额
    score: '*', // 积分
    banners: [],
    encryptedData: "",
    iv: '',
    showPhone: false
  },
  onLoad: function() {
    /**
     * 先获取本地数据，查看是否有用户信息数据，
     * 如果有，直接那本地数据初始化界面，
     * 否则，提示用户手动授权登录，获取信息
     */
    try {
      var _userInfo = auth.getUser();
      if (_userInfo) {
        console.log(_userInfo)
        // Do something with return value
        this.setData({
          userInfo: _userInfo.wxaUser,
          hasUserInfo: true,
          mobile: _userInfo.member.mobile,
          memberId: _userInfo.member.id
        })
        if (this.data.memberId) {
          this.queryCoupon(1, 0, this.data.memberId);
          this.getMbrBalance();
          this.queryScore();
        }
      }
    } catch (e) {
      // Do something when catch error
    }
    // 获取banner
    this.getBanners();
  },

  /**
   * 获取banner图资源
   * 获取会员小程序首页banner
   */
  getBanners: function() {
    bannerService.getBannerList('WXAPPHOME').then(res => {
      this.setData({
        banners: res
      })
    }).catch(err => {
      wx.showToast({
        title: err.message,
        icon: 'none',
        duration: 2000
      })
    })
  },
  /**
   * 查询用户相关的券
   * 调两个接口，一个内部券，一个外部券
   */
  queryCoupon: function(page, pageSize, memberId) {
    var tempAllCouponCount = 0;
    // 查询内部券，将查到的券相加
    couponService.queryCoupon(page, pageSize, memberId).then(res => {
      // console.log(res)
      if (res.records && res.records.length > 0) {
        let count = 0;
        res.records.forEach(item => {
          if (item.status === 'OPEN')
            count++
        })
        tempAllCouponCount += count;
      }

      let couponData = {
        memberId: memberId
      }
      // 查询外部券
      return couponService.queryExternalCoupons(couponData)
    }).then(res => {
      // console.log(res)
      if (res && res.length > 0) {
        let count = 0;
        res.forEach(item => {
          if (item.status === 'OPEN')
            count++
        })
        tempAllCouponCount += count;
        this.setData({
          couponCount: tempAllCouponCount
        })
      } else {
        this.setData({
          couponCount: '*'
        })
      }
    }).catch(err => {
      wx.showToast({
        title: err.message,
        icon: 'none',
        duration: 2000
      })
    })
  },
  /**
   * 查询储值余额
   */
  getMbrBalance: function() {
    memberService.getMbrBalance().then(res => {
      this.setData({
        storedValue: res
      })
    }).catch(err => {
      wx.showToast({
        title: err.message,
        icon: 'none',
        duration: 2000
      })
    })
  },
  /**
   * 查询积分
   */
  queryScore: function() {
    memberService.getBalance(this.data.mobile).then(res => {
      this.setData({
        score: res
      })
    }).catch(err => {
      wx.showToast({
        title: err.message,
        icon: 'none',
        duration: 2000
      })
    })
  },
  /**
   * 校验权限，判断是否登录，授权登录后才可以进入二级页面查看
   */
  checkAuthor: function() {
    if (this.data.hasUserInfo) {
      return true;
    } else {
      wx.showToast({
        title: "点击头像授权登录后才能查看哦~",
        icon: 'none',
        duration: 2000
      })
      return false
    }
  },
  // 跳转到储值充值中心
  toStoredValue: function() {
    if (this.checkAuthor()) {
      wx.navigateTo({
        url: '../balance/storedValue/storedValue'
      })
    }
  },
  // 跳转到我的优惠券
  toMyCoupon: function() {
    if (this.checkAuthor()) {
      wx.navigateTo({
        url: '../coupon/myCoupon/myCoupon'
      })
    }
  },
  // 跳转到领券中心
  toCouponCenter: function() {
    // wx.showToast({
    //   title: '该功能暂未开放，敬请期待',
    //   icon: 'none',
    //   duration: 2000
    // })
    if (this.checkAuthor()) {
      wx.navigateTo({
        url: '../coupon/couponCenter/couponCenter',
      })
    }
  },
  // 跳转到我的积分
  toScore: function() {
    if (this.checkAuthor()) {
      wx.navigateTo({
        url: '../score/score',
      })
    }
  },
  // 跳转到我的会员卡
  toMyCard: function() {
    if (this.checkAuthor()) {
      wx.navigateTo({
        url: '../myCard/myCard',
      })
    }
  },
  // 跳转到我的礼品卡
  toGiftCard: function() {
    if (this.checkAuthor()) {
      wx.navigateTo({
        url: '../giftCard/giftCard/giftCard',
      })
    }
  },
  // 跳转到积分商城
  toScoreMall: function() {
    // wx.showToast({
    //   title: '该功能暂未开放，敬请期待',
    //   icon: 'none',
    //   duration: 2000
    // })
    if (this.checkAuthor()) {
      wx.navigateTo({
        url: '../scoreMall/scoreMall/scoreMall',
      })
    }
  },
  /**
   * 下拉刷新
   */
  onPullDownRefresh: function() {
    this.setData({
      userInfo: {},
      mobile: '',
      couponCount: 0,
      storedValue: 0,
      score: 0,
      hasUserInfo: false
    })
    this.onLoad();
    wx.stopPullDownRefresh();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },

  /**
   * banner图点击事件，会员小程序只支持跳转到小程序有的模块中
   * 未授权登录，不进行跳转
   */
  handelBannerClick: function(e) {
    let clickItem = ''
    this.data.banners.forEach(item => {
      if (item.id === e.currentTarget.dataset.id) {
        console.log(item)
        clickItem = item;
      }
    })
    // 授权登录后才能根据banner 的跳转类型进行跳转
    if (this.checkAuthor()) {
      // 只跳转应用内模块，不跳转链接，商品等
      if (clickItem.linkType === 'APP') {
        if (clickItem.appReturnType === 'MEMBER_CARD') {
          // 如果跳转类型是会员卡，跳转到会员码页面
          wx.navigateTo({
            url: '../myCard/myCard',
          })
        } else if (clickItem.appReturnType === 'RECHARGE') {
          // 如果跳转类型是充值，跳转到储值充值界面
          wx.navigateTo({
            url: '../balance/storedValue/storedValue',
          })
        } else if (clickItem.appReturnType === 'GIFTCARD') {
          // 如果跳转类型是礼品卡，跳转到礼品卡界面
          wx.navigateTo({
            url: '../giftCard/giftCard/giftCard'
          })
        }
      } else if (clickItem.linkType === "GIFTCARDACTIVITYDETAILS") {
        // 如果跳转类型是礼品卡详情，根据giftcardActivityId跳转到礼品卡详情页
        wx.navigateTo({
          url: '../giftCard/giftCardBuy/giftCardBuy?giftCardActivityId=' + clickItem.giftcardActivityId
        })
      }
    }
  },

  // 用户登录组件事件处理
  handleUserLogin: function () {
    var userInfo = app.globalData.userInfo;
    console.log(userInfo)
    const self = this
    if (userInfo) {
      this.setData({
        userInfo: {
          ...userInfo.wxaUser
        }
      })
      if (userInfo.member) {
        // 如果会员信息存在，填充页面会员信息，查询储值余额，积分，优惠券等
        self.setData({
          hasUserInfo: true,
          mobile: userInfo.member.mobile,
          memberId: userInfo.member.id
        })
        self.queryCoupon(1, 0, userInfo.member.id);
        self.getMbrBalance();
        self.queryScore();
      } else {
        self.setData({
          userInfo: userInfo.wxaUser,
          hasUserInfo: true,
        })
        self.handlePopupPhone();
      }
    }
  },
  handleTabbar: function (e) {
    console.log(e.detail)
    if (e.detail.showTabbar === true) {
      this.setData({
        showTabbar: e.detail.showTabbar
      })
    } else {
      this.setData({
        showTabbar: e.detail.showTabbar
      })
    }
  },
  handlePopupPhone: function () {
    if (!app.globalData.userInfo.member) {
      this.setData({
        showPhone: true
      });
    } else {
      this.setData({
        showPhone: false
      })
    }
  },
  handleBindPhone: function (e) {
    if (e.detail.bindMobile === true) {
      this.handlePopupPhone()
    }
  }
})